import { Channels } from '/imports/models/Channels';

Template.homepage.onCreated(function () {
  this.user = new ReactiveVar();
  this.limit = new ReactiveVar(15);
  this.hasMore = new ReactiveVar(false);

  this.autorun(() => {
    const username = Router.current().params.username;
    Meteor.call('getUser', username, (err, res) => {
      if (res) {
        this.user.set(res);
      }
    });
  });

  this.autorun(() => {
    const user = this.user.get();
    if (user) {
      this.sub = this.subscribe('get.user.channels', { userId: user._id }, this.limit.get());
      this.total = Counts.get('get.user.channels.counts');
      if (this.total > this.limit.get()) {
        this.hasMore.set(true);
      } else {
        this.hasMore.set(false);
      }
    }
  });
});

Template.homepage.helpers({
  display: function () {
    const user = Template.instance().user.get();

    if (user && user.profile && user.profile.name) {
      return user.profile.name;
    }

    if (user && user.emails) {
      return user.emails[0].address;
    }

    return '';
  },

  username: function () {
    const user = Template.instance().user.get();

    if (user && user.username) {
      return user.username;
    }

    return '';
  },

  avatar: function () {
    const user = Template.instance().user.get();

    if (user && user.profile) {
      return user.profile.avatar;
    }

    return '';
  },

  notes: function () {
    const user = Template.instance().user.get();

    if (user && user.profile) {
      return user.profile.notes;
    }

    return '';
  },

  channels: function () {
    if (Template.instance().user.get() && Template.instance().sub.ready()) {
      return Channels.find({
        'owner.id': Template.instance().user.get()._id
      }, {
        limit: Template.instance().limit.get(),
        sort: {
          createdAt: -1
        }
      });
    }
  },

  hasMore: function () {
    return Template.instance().hasMore.get();
  }
});

Template.homepage.events({
  'click #homepage-loadmore' (e, instance) {
    let limit = instance.limit.get();
    if (instance.total > limit) {
      instance.limit.set(limit + 15);
    }
  }
});